package com.sfang.common.extension;


import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import org.apache.skywalking.apm.toolkit.log.logback.v1.x.log.GRPCLogClientAppender;
import org.apache.skywalking.apm.toolkit.log.logback.v1.x.mdc.TraceIdMDCPatternLogbackLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class CustomLogbackAppender implements ApplicationRunner {

    private static Logger LOGGER = LoggerFactory.getLogger(CustomLogbackAppender.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

            //layout
            TraceIdMDCPatternLogbackLayout layout = new TraceIdMDCPatternLogbackLayout();
            layout.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{tid}] [%thread] %-5level %logger{36} -%msg%n");
            layout.setContext(lc);
            layout.start();

            //encoder
            LayoutWrappingEncoder encoder = new LayoutWrappingEncoder();
            encoder.setLayout(layout);
            encoder.start();

            //appender
            GRPCLogClientAppender grpcLogClientAppender = new GRPCLogClientAppender();
            grpcLogClientAppender.setEncoder(encoder);
            grpcLogClientAppender.setContext(lc);
            grpcLogClientAppender.start();

            ch.qos.logback.classic.Logger logbackLogger =
                    (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

            logbackLogger.addAppender(grpcLogClientAppender);
        } catch (Exception e) {
            LOGGER.error(String.format("customLogbackAppender error"), e);
        }
    }
}
